import network
import json
import requests
import json
from utils import common
from lib.config.index import device_config, wifi_config
from utils import device

hostname = device_config.get_hostname()
network.hostname(hostname)
wlan = network.WLAN(network.STA_IF)


def connect_WIFI(ssid, password):
    """连接WIFI"""
    global wlan
    wlan.active(True)

    txpower_value = wifi_config.get_txpower()
    if txpower_value:
        wlan.config(txpower=txpower_value)  # 部分C3设备天线缺陷需要降低功率
    if not wlan.isconnected():
        print("wlan: connecting to network...")
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            pass
        print(f"wlan: connect {ssid} success")
    if wifi_config.is_debug():
        print("wlan: ifconfig:", wlan.ifconfig())
    device.update_device_net_info()


def disconnectWIFI():
    global wlan
    if wlan.isconnected():
        wlan.disconnect()


def HTTP_GET(request_url, params, type="json"):
    """
    HTTP GET
    return raw or json
    """
    params_str = "?"
    for key in params:
        value = params[key]
        if isinstance(value, str):
            value = str(value.encode())[1:].replace("\\x", "%").replace("'", "")
            # print(value)
        params_str = params_str + f"{key}={value}&"
    params_str = params_str[0:-1]
    request_url = f"{request_url}{params_str}"
    response = requests.get(request_url)

    if type == "raw":
        return response
    json_data = json.loads(response.content)
    return json_data


def HTTP_POST(request_url, payload, type="json"):
    """HTTP POST"""
    payload = json.dumps(payload).encode("utf8")
    # print(payload)
    response = requests.post(
        request_url, headers={"content-type": "application/json"}, data=payload
    )
    # print(response)
    if type == "raw":
        return response

    json_data = json.loads(response.content)
    return json_data


# 测试

if __name__ == "__main__":
    from lib.net import wifi

    wifi.do_connect()

    def GET_TTS():
        common.print_gc_info()
        params = {
            "Text": "寒雨连江夜入吴，平明送客楚山孤",
            "Codec": "wav",
            "EmotionCategory": "poetry",
            "VoiceType": 301000,
        }
        response = HTTP_GET("http://www.hanxiaoxin.cn:8080/tts", params, "raw")
        raw = response.raw
        audio_file = open("/audio.wav", "wb")
        while True:
            recv = raw.read(1024)
            # print(type(recv))
            if not recv:
                break
            audio_file.write(recv)
        audio_file.close()
        common.print_gc_info()

    def POST_TTS():
        json_data = HTTP_POST(
            "http://www.hanxiaoxin.cn:8080/tts", {"Text": "1", "Codec": "wav"}
        )
        audio_base64 = json_data["Audio"]
        audio_data = common.decode_base64(audio_base64)
        print(len(audio_data))
        with open("/audio.wav", "w") as f:
            f.write(audio_data)

    def GET_HTML():
        params = {"time": 123}
        response = HTTP_GET("http://www.hanxiaoxin.cn", params, "raw")
        print(response)

    GET_HTML()
